<template>
	<div>
		<div class="search">
			<a-form :model="searchForm">
				<a-row :gutter="20">
					<a-col :span="4">
						<a-select ref="select" v-model:value="searchForm.status" @focus="focus" @change="selectXZname"
							placeholder="请选择门店状态" style="width: 200px">
							<a-select-option v-for="item in storeStatusList" :value="item.id"
								:key="item.id">{{ item.name }}</a-select-option>
						</a-select>
					</a-col>
					<a-col :span="6">
						<a-form-item label="门店名称" name="hospital_name">
							<a-input placeholder="请输入门店名称" v-model:value="searchForm.hospital_name"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="门店code" name="hospital_code">
							<a-input placeholder="请输入门店code" v-model:value="searchForm.hospital_code"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="门店地址" name="address">
							<a-input placeholder="请输入门店地址" v-model:value="searchForm.address"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="2">
						<a-button type="primary" class="d-a-center">搜索</a-button>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<a-row style="margin-bottom: 20px">
			<a-col :span="2">
				<a-button type="primary" v-has="{ a: $route, b: 2 }" @click="add" class="d-a-center">创建门店</a-button>
			</a-col>
			<a-col :span="2" style="margin-left: 5px">
				<a-upload v-model:file-list="contentImg" name="file" :maxCount="1" :customRequest="handleChangeFile"
					:beforeUpload="beforeUpload1">
					<a-button class="d-a-center" type="primary">
						<upload-outlined></upload-outlined>
						导入门店
					</a-button>
				</a-upload>
			</a-col>
			<a-col :span="2" style="margin-left: 5px">
				<a-button type="primary" @click="bind" class="d-a-center">绑定服务</a-button>
			</a-col>
		</a-row>

		<a-table :columns="colums" :data-source="list" bordered :loading="loading" :pagination="pagination"
			@change="handleTableChange" :scroll="{ y: 540 }" :scrollToFirstRowOnChange="true">
			<template #operation="{ record }">
				<div>
					<a-button type="link" @click="look(record.id)" v-has="{ a: $route, b: 1 }">查看</a-button>
					<!--  <a-button
            type="link"
            @click="edit(record.id)"
            v-has="{ a: $route, b: 2 }"
            >更新</a-button
          > -->
					<a-button type="link" @click="contact(record.id)" v-has="{ a: $route, b: 2 }">
						关联商品</a-button>
					<!-- <a-button
            type="link"
            danger
            @click="del(record.id)"
            style="margin-left: 10px"
            v-has="{ a: $route, b: 2 }"
            >下架</a-button
          > -->
				</div>
			</template>
		</a-table>
		<a-modal :visible="visible" :title="title(editType)" @cancel="close('visible')" width="80%" :footer="null">
			<a-form :model="form" ref="formRef" :rules="rules" :label-col="labelCol">
				<a-row :gutter="20">
					<a-col :span="8">
						<a-form-item label="所属城市" name="city_name">
							<a-input-group>
								<a-auto-complete v-model:value="form.city_name" :options="cityList" style="width: 100%"
									@input="searchCity" placeholder="请选择城市" />
							</a-input-group>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="城市code" name="city_code">
							<a-input placeholder="请输入城市code" v-model:value="form.city_code"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="门店类型" name="key_word">
							<a-select ref="select" v-model:value="form.key_word" @focus="focus" placeholder="请选择门店类型">
								<a-select-option v-for="item in storeTypeList" :value="item.id"
									:key="item.id">{{ item.name }}</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="20">
					<a-col :span="8">
						<a-form-item label="门店名称" name="hospital_name">
							<a-input placeholder="请输入门店名称" v-model:value="form.hospital_name"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="门店code" name="hospital_code">
							<a-input placeholder="请输入门店code" v-model:value="form.hospital_code"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="工作时间" name="work_time">
							<a-input placeholder="请输入工作时间" v-model:value="form.work_time"></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="20">
					<a-col :span="12">
						<a-form-item label="门店地址" name="address">
							<a-input-group>
								<a-auto-complete v-model:value="form.address" :options="addressList" style="width: 100%"
									@input="searchAddress" placeholder="请输入门店地址" />
							</a-input-group>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="经度" name="point_x">
							<a-input placeholder="请输入地址经度" v-model:value="form.point_x"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="纬度" name="point_y">
							<a-input placeholder="请输入地址纬度" v-model:value="form.point_y"></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="20">
					<a-col :span="8">
						<a-form-item label="logo图片">
							<a-upload v-model:file-list="fileList" list-type="picture-card" class="avatar-uploader"
								:maxCount="1" :customRequest="uploadLogo" :before-upload="beforeUpload"
								@change="handleChange">
								<div v-if="fileList.length < 1" class="ant-upload-text">
									<plus-outlined />
								</div>
							</a-upload>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="环境图片(第一张为头图）">
							<a-upload v-model:file-list="env_imgs_url" list-type="picture-card" class="avatar-uploader"
								:maxCount="5" :customRequest="uploadEnviroment">
								<div v-if="env_imgs_url.length < 5" class="ant-upload-text">
									<plus-outlined />
								</div>
							</a-upload>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="20">
					<a-col :span="8">
						<a-form-item label="营业执照">
							<a-upload v-model:file-list="business_license" list-type="picture-card"
								class="avatar-uploader" :maxCount="1" :customRequest="uploadBuisness">
								<div v-if="business_license.length < 1" class="ant-upload-text">
									<plus-outlined />
								</div>
							</a-upload>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="医疗机构执业许可证">
							<a-upload v-model:file-list="medical_license" list-type="picture-card"
								class="avatar-uploader" :maxCount="1" :customRequest="uploadMedical">
								<div v-if="medical_license.length < 1" class="ant-upload-text">
									<plus-outlined />
								</div>
							</a-upload>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="20">
					<a-col :span="12">
						<a-form-item label="门店简介" name="detail">
							<a-textarea placeholder="请输入门店简介" v-model:value="form.detail"></a-textarea>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="20">
					<a-col :span="12">
						<a-form-item label="门店通知" name="notify">
							<a-textarea placeholder="请输入门店通知" v-model:value="form.notify"></a-textarea>
						</a-form-item>
					</a-col>

					<a-col :span="8">
						<a-form-item label="门店联系电话" name="tel">
							<a-input placeholder="请输入门店联系电话" v-model:value="form.tel"></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="20">
					<a-col :span="24">
						<a-form-item label="预约须知" name="note_category">
							<a-textarea style="width: 80%" :rows="6" placeholder="请输入预约须知"
								v-model:value="form.note_category"></a-textarea>
						</a-form-item>
					</a-col>
				</a-row>
				<a-divider></a-divider>
				<a-row justify="space-around" :gutter="20">
					<a-col :span="4">
						<a-button type="info" @click="close('visible')" class="d-a-center">关闭</a-button>
					</a-col>
					<a-col :span="4" v-if="editType != 2">
						<a-button type="primary" @click="submit" class="d-a-center">提交审核</a-button>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>

		<a-modal :visible="storeVisible" title="关联商品" @ok="close('storeVisible')" @cancel="close('storeVisible')"
			okText="关闭">
			<a-table :columns="colums1" :data-source="productList" bordered :loading="loading1" :scroll="{ y: 540 }">
			</a-table>
		</a-modal>
		<!-- 展示门店导入的数据 -->
		<a-modal :visible="importVisible" title="导入的门店数据" okText="确认导入" @cancel="close('importVisible')"
			>
			<a-table :dataSource="importDataList" :columns="columns1" />
		</a-modal>
		<!-- 绑定服务的弹窗 -->
		<a-modal :visible="bindVisible" title="门店和服务绑定" okText="绑定" @cancel="close('bindVisible')"
			 width="100%">
			<template #footer>
				<div class="d-j-around">
					<a-button @click="cancleOrder('bindVisible')" class="d-a-center">取消</a-button>
					<a-button type="primary" @click="bindSubmit" class="d-a-center">绑定</a-button>
					<a-button type="primary" @click="bindAll" class="d-a-center">绑定全部</a-button>
				</div>
			</template>
			<a-form ref="searchRef" :rules="rules1" :model="searchForm" :hideRequiredMark="true"
				style="margin-bottom: 20px">
				<!-- 门店搜索 -->
				<a-row>
					<a-col :span="8">
						<a-form-item label="城市名称">
							<a-input placeholder="请输入城市名称" v-model:value="searchForm.cityName" allow-clear />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="门店code">
							<a-input-number style="width: 100px; text-align: center" placeholder="请输入门店code" :min="0"
								allow-clear v-model:value="searchForm.codeSmall" />
							<a-input style="
                  width: 30px;
                  border-left: 0;
                  pointer-events: none;
                  backgroundcolor: #fff;
                " placeholder="~" disabled />
							<a-input-number :maxLength="5" allow-clear
								style="width: 100px; text-align: center; border-left: 0" placeholder="请输入门店code"
								v-model:value="searchForm.hospital_code" />
						</a-form-item>
						<a-text style="font-size: 12px">（如果搜索单个门店，请按照“2~2”这样的方式搜索）</a-text>
					</a-col>

					<a-col :span="2" style="margin-left: 20px">
						<a-button type="primary" class="d-a-center" @click="search">搜索</a-button>
						<!-- <a-button
              type="primary"
              class="d-a-center"
              @click="bindAll"
              style="margin-top: 15px"
              >绑定全部</a-button
            > -->
					</a-col>
				</a-row>
			</a-form>
			<!-- <a-form
        ref="searchRef"
        :rules="rules1"
        :model="searchFor1"
        :hideRequiredMark="true"
        style="margin-bottom: 20px"
      >
        <a-row>
          <a-col :span="8" style="margin-left: 320px">
            <a-form-item label="搜索服务" name="groupName">
              <a-input
                placeholder="请输入服务名称"
                allowClear="true"
                v-model:value="searchForm1.groupName"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="2" style="margin-left: 20px">
            <a-button type="primary" class="d-a-center" @click="search1"
              >搜索</a-button
            >
          </a-col>
        </a-row>
      </a-form> -->

			<div style="display: flex">
				<!-- 门店列表 :row-selection="rowSelection"-->
				<a-table preserveSelectedRowKeys="true" :columns="storeSolums" :data-source="list" bordered
					:loading="loading" :pagination="pagination" :rowSelection="rowSelection" row-key="id"
					@change="handleTableChange">
				</a-table>
				<!-- 服务列表 -->
				<a-table :columns="shopSolums" :data-source="shopListNum" bordered :loading="loading"
					:pagination="shopPagination" @change="shopHandleTableChange" :row-selection="rowSelection1"
					style="margin-left: 80px">
					<template #contractPrice="{ record }">
						{{ record.contractPrice / 100 }}
					</template>
				</a-table>
			</div>
		</a-modal>
	</div>
</template>
<script>
	import {
		reactive,
		createVNode,
		toRefs,
		ref,
		computed,
		watch,
		watchEffect,
		nextTick,
	} from "vue";
	import {
		message,
		Modal
	} from "ant-design-vue";
	import {
		deleteObjBlank
	} from "@/assets/js/common.js";
	import {
		uploadPicture,
		updateStore,
		getStoreList,
		updateShopStatus,
		selectShopById,
		excelPublishShopAPI,
		getProductList,
		shopBindingGoodAPI,
	} from "@/api/service/index.js";
	import {
		throttle
	} from "@/assets/js/debounceThrottle";
	import {
		ExclamationCircleOutlined,
		EditOutlined,
		PlusOutlined,
		UploadOutlined,
	} from "@ant-design/icons-vue";
	import xlsx from "xlsx"; //这个最新版本的会报错最好装低版本本
	import axios from "axios";
import { useModal } from "@/hooks"

	export default {
		components: {
			PlusOutlined,
		},
		setup() {
			const searchRef = ref("");
			const data = reactive({
				selectList: [],
				selectList1: [],
				bindVisible: false,
				loading: true,
				searchForm: {},
				searchForm1: {},
				list: [],
				form: {},
				visible: false,
				fileList: [],
				env_imgs_url: [], //环境图片、第一章是头图
				business_license: [], //营业执照图片
				medical_license: [], //医疗机构证
				cityList: [{
						value: "杭州市"
					},
					{
						value: "上海市"
					},
					{
						value: "北京市"
					},
					{
						value: "深圳市"
					},
					{
						value: "林芝市"
					},
				], //城市列表
				addressList: [], //地址列表
				formRef: "",
				uploadLoading: false,
				imageUrl: "",
				editType: 0, // 0 新增 1编辑 2查看
				storeVisible: false,
				productList: [], //关联的商品列表
				loading1: false,
				contentImg: [],
				excelForm: {},
				storeList: [], //绑定门店列表
				shopListNum: [],
			});
			// 分页器
			const page = reactive({
				current: 1,
				pageSize: 10,
				total: 0,
			});
			//商品列表分页器
			const shopPage = reactive({
				current: 1,
				pageSize: 10,
				total: 0,
			});
			const rules1 = {
				//  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
				//  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
			};
			const rules = reactive({
				tel: [{
					required: true,
					message: "门店联系电话",
					trigger: "blur"
				}],
				city_name: [{
					required: true,
					message: "请输入城市",
					trigger: "blur"
				}],
				city_code: [{
					required: true,
					message: "请输入城市编码",
					trigger: "blur"
				}, ],
				key_word: [{
					required: true,
					message: "请选择医院等级"
				}],
				point_x: [{
					required: true,
					message: "请输入门店经度",
					trigger: "blur"
				}],
				point_y: [{
					required: true,
					message: "请输入门店纬度",
					trigger: "blur"
				}],
				address: [{
					required: true,
					message: "请输入门店地址",
					trigger: "blur"
				}],
				work_time: [{
					required: true,
					message: "请输入工作时间",
					trigger: "blur"
				}, ],
				hospital_name: [{
					required: true,
					message: "请输入门店名称",
					trigger: "blur"
				}, ],
				hospital_code: [{
					required: true,
					message: "请输入门店code，机构保证唯一",
					trigger: "blur",
				}, ],
			});
			const storeStatusList = [{
					name: "已上架",
					id: 1,
				},
				{
					name: "未通过",
					id: 2,
				},
				{
					name: "已下架",
					id: 3,
				},
				{
					name: "审核中",
					id: 0,
				},
			];
			const storeTypeList = [{
					name: "公立",
					id: "公立",
				},
				{
					name: "民营",
					id: "民营",
				},
				{
					name: "连锁",
					id: "连锁",
				},
				{
					name: "二甲",
					id: "二甲",
				},
				{
					name: "社区卫生院",
					id: "社区卫生院",
				},
			];
			const orderStatus = (status) => {
				let title = "";
				switch (status) {
					case 0:
						title = "已上架";
						break;
					case 1:
						title = "审核中";
						break;
					case 2:
						title = "未通过";
						break;
					case 3:
						title = "已下架";
						break;
					default:
						break;
				}
				return title;
			};
			const title = (status) => {
				let title = "";
				switch (status) {
					case 2:
						title = "查看门店";
						break;
					case 0:
						title = "新增门店";
						break;
					case 1:
						title = "编辑门店";
						break;
					default:
						break;
				}
				return title;
			};

			const colums = [{
					title: "门店code",
					dataIndex: "hospital_code",
					className: "table",
				},
				{
					title: "门店名称",
					dataIndex: "hospital_name",
					className: "table",
				},
				{
					title: "门店类型",
					dataIndex: "xzName",
					className: "table",
				},
				{
					title: "门店地址",
					dataIndex: "address",
					className: "table",
				},
				{
					title: "门店状态",
					dataIndex: "status",
					className: "table",
					slots: {
						customRender: "status",
					},
				},

				{
					title: "操作",
					dataIndex: "operation",
					className: "table",
					fixed: "right",
					// width: 150,
					// align: "center",
					slots: {
						customRender: "operation",
					},
				},
			];
			const colums1 = [{
					title: "商品ID",
					dataIndex: "number",
					className: "table",
				},
				{
					title: "商品名称",
					dataIndex: "hdName",
					className: "table",
				},
				{
					title: "售卖价",
					dataIndex: "xzName",
					className: "table",
				},
			];
			const shopSolums = [{
					title: "商品ID",
					dataIndex: "id",
					className: "table",
				},
				{
					title: "商品名称",
					dataIndex: "groupName",
					className: "table",
				},
				{
					title: "售卖价格",
					dataIndex: "contractPrice",
					className: "table",
					slots: {
						customRender: "contractPrice",
					},
				},
			];
			const storeSolums = [{
					title: "id",
					dataIndex: "id",
					className: "table",
				},
				{
					title: "门店code",
					dataIndex: "hospitalCode",
					className: "table",
				},
				{
					title: "门店名称",
					dataIndex: "hospitalName",
					className: "table",
				},
				{
					title: "门店地址",
					dataIndex: "address",
					className: "table",
				},
			];
			const orderListStatusColor = computed((status) => {
				return function(status) {
					if (status == 0) {
						return "#f50";
					}
					if (status == 1) {
						return "success";
					}
					if (status == 2) {
						return "cyan";
					}
					if (status == 3) {
						return "warning";
					}
				};
			});
			// 分页器/-
			const pagination = computed(() => ({
				current: page.current,
				pageSize: page.pageSize,
				pageSizeOptions: ["10", "20", "30"],
				showTotal: (total, range) => {
					return "共" + total + "条";
				},
				total: page.total,
				showQuickJumper: true,
				showSizeChanger: true,
			}));
			const shopPagination = computed(() => ({
				current: shopPage.current,
				pageSize: shopPage.pageSize,
				pageSizeOptions: ["10", "20", "30"],
				showTotal: (total, range) => {
					return "共" + total + "条";
				},
				total: shopPage.total,
				showQuickJumper: true,
				showSizeChanger: true,
			}));
			const cancleOrder = (e) => {
				data[e] = false;
				if (e == "bindVisible") {
					data.selectList = [];
					data.searchForm = {};
					selectedRowKeys1.value = [];
					selectedRowKeys.value = [];
				}
			};
			const close= (e) => {
				console.log(data[e])
				data[e] = false;
			};
			const add = () => {
				data.visible = true;
				data.editType = 0;
			};
			const edit = (id) => {
				initDetail(id);
				data.visible = true;
				data.editType = 1;
			};
			const handleChange = (info) => {
				if (info.file.status === "uploading") {
					data.uploadLoading = true;
					return;
				}
				if (info.file.status === "done") {
					// Get this url from response in real world.
					getBase64(info.file.originFileObj, (base64Url) => {
						//   data.imageUrl = base64Url;
						data.uploadLoading = false;
					});
				}

				if (info.file.status === "error") {
					data.uploadLoading = false;
					message.error("上传错误");
				}
			};
			//绑定全部的按钮
			const bindAll = () => {
				// 先搜索,调第一次，拿到total
				page.current = 1;
				async function init() {
					let obj = {
						pageNum: page.current,
						pageSize: page.pageSize,
						...data.searchForm,
					};
					let res = await getStoreList(obj);
					if (res.success) {
						data.list = res.object.list;
						page.total = res.object.total;
						data.loading = false;
					}
					let total = page.total;
					console.log("11111111111111111", total);
					return total;
				}
				// init();
				init().then((total) => {
					console.log(915, total);
					let obj1 = {
						pageNum: page.current,
						pageSize: total,
						...data.searchForm,
					};
					//现在获取到了所有的total
					getStoreList(obj1)
						.then((res) => {
							console.log(924, res.object.list);
							let shopId = [];
							if (res.object.list.map((item) => item.id)) {
								let id = Object.values(
									res.object.list.map((item) => item.id)
								).map((m) => {
									return Number(m);
								});
								shopId = id;
							}
							console.log(923, shopId);
							return shopId; // 将shopId作为返回值返回
						})
						.then((shopId) => {
							console.log(939, shopId);
							//现在获取商品的id
							if (selectedRowKeys1.value.length == 0) {
								message.warning("请选择你要绑定的商品");
								return;
							}
							const {closeModal} = useModal.confirm({
								title: `确认绑定当前门店和服务吗?`,
								icon: createVNode(ExclamationCircleOutlined),
								onOk: async () => {
									let goodId = [];
									if (selectedRowKeys1.value.length) {
										let id = Object.values(selectedRowKeys1.value).map((m) => {
											return Number(m);
										});
										goodId = id;
									}
									console.log(goodId);
									shopBindingGoodAPI({
										shopId,
										goodId
									}).then((res) => {
										console.log(res);
										if (res.success) {
											message.success("绑定成功");
										}
										data.bindVisible = false;
										selectedRowKeys1.value = [];
										selectedRowKeys.value = [];
										closeModal()

									});
										},
									});
							
						});
				});
			};
			//门店服务绑定的搜索
			const search = () => {
				page.current = 1;
				init();
			};
			//绑定 bindSubmit
			const bindSubmit = () => {
				if (selectedRowKeys.value.length == 0) {
					message.warning("请选择你要绑定的门店");
					return;
				}
				if (selectedRowKeys1.value.length == 0) {
					message.warning("请选择你要绑定的服务");
					return;
				}
				console.log(selectedRowKeys1.value);
				const {closeModal} = useModal.confirm({
					title: `确认绑定当前门店和服务吗?`,
					icon: createVNode(ExclamationCircleOutlined),
					onOk: async () => {
						let shopId = [];
						if (selectedRowKeys.value.length) {
							let id = Object.values(selectedRowKeys.value).map((m) => {
								return Number(m);
							});
							shopId = id;
						}
						console.log(shopId);

						let goodId = [];
						if (selectedRowKeys1.value.length) {
							let id = Object.values(selectedRowKeys1.value).map((m) => {
								return Number(m);
							});
							goodId = id;
						}
						console.log(goodId);
						shopBindingGoodAPI({
							shopId,
							goodId
						}).then((res) => {
							console.log(res);
							if (res.success) {
								message.success("绑定成功");
							}
							data.bindVisible = false;
							selectedRowKeys1.value = [];
							selectedRowKeys.value = [];
							closeModal()
						});
					},
				});
				
			};
			const bind = () => {
				data.bindVisible = true;
				init();
				//调商品列表的接口
				shopList();
			};
			//商品列表
			async function shopList() {
				let obj = {
					pageNum: shopPage.current,
					pageSize: shopPage.pageSize,
					...data.searchForm1,
				};
				let res = await getProductList(obj);
				// console.log(res);
				if (res.success) {
					res.object.list.map((el) => (el.key = el.id));
					data.shopListNum = res.object.list;
					shopPage.total = res.object.total;
					data.loading = false;
				}
			}
			const selectedRowKeys1 = ref([]);
			//服务全选反选
			const rowSelection1 = ref({
				checkStrictly: false,
				preserveSelectedRowKeys: true,
				selectedRowKeys: selectedRowKeys1,
				onSelect: (record, selected, selectedRows) => {
					// console.log(record, selected, selectedRows,'选择多项');
					if (selected) {
						selectedRowKeys1.value = [...selectedRowKeys1.value, record.id];
					} else {
						selectedRowKeys1.value = selectedRowKeys1.value.filter(
							(item) => item != record.id
						);
					}
				},
				onSelectAll: async (selected, selectedRows, changeRows) => {
					// console.log("selected", selected);
					// console.log("selectedRows", selectedRows);
					// console.log("changeRows", changeRows);
					const changeIds = changeRows.map((item) => item.id);
					if (selected) {
						selectedRowKeys1.value = [...selectedRowKeys1.value, ...changeIds];
					} else {
						selectedRowKeys1.value = selectedRowKeys1.value.filter((item) => {
							!changeIds.includes(item);
						});
					}
				},
			});
			//门店全选反选
			// const rowSelection = () => {
			//   console.log("firstMetaTableSelectedRowKeys");
			//   console.log("firstMetaTableselectedRows");
			// };

			const selectedRowKeys = ref([]);

			const rowSelection = ref({
				// selectedRowKeys,
				preserveSelectedRowKeys: true,
				checkStrictly: false,
				selectedRowKeys,
				onSelect: (record, selected, selectedRows) => {
					// console.log(record, selected, selectedRows,'选择多项');
					if (selected) {
						selectedRowKeys.value = [...selectedRowKeys.value, record.id];
					} else {
						selectedRowKeys.value = selectedRowKeys.value.filter(
							(item) => item != record.id
						);
					}
				},
				onSelectAll: async (selected, selectedRows, changeRows) => {
					// console.log("selected", selected);
					// console.log("selectedRows", selectedRows);
					// console.log("changeRows", changeRows);
					const changeIds = changeRows.map((item) => item.id);
					if (selected) {
						selectedRowKeys.value = [...selectedRowKeys.value, ...changeIds];
					} else {
						selectedRowKeys.value = selectedRowKeys.value.filter((item) => {
							!changeIds.includes(item);
						});
					}
				},
			});
			//批量上传门店
			const handleChangeFile = (file) => {
				console.log(file);
				uploadImage1(file, "contentImg");
			};
			const uploadImage1 = async (file, e) => {
				let formData = new FormData();
				formData.append("file", file.file);
				let res = await excelPublishShopAPI(formData, "ali");
				console.log(res);
				data[e] = data[e].filter((el) => el.status == "done");
				if (res.success) {
					data.excelForm["excelPath"] = res.object;
					data[e].push({
						uid: file.file.uid,
						url: res.object,
						status: "done",
						name: file.file.name,
					});
				}
				console.log(data[e], "data[e]是--");
			};
			const beforeUpload1 = () => {
				return new Promise((resolve, reject) => {
					if (data.contentImg.length > 0) {
						message.error("请删除已存在的文件再上传");
						reject(false);
					}
					resolve(true);
				});
			};

			const beforeUpload = (file) => {
				console.log("上传logo图片----");
				const isJpgOrPng =
					file.type === "image/psd" ||
					file.type === "image/bmp" ||
					file.type === "image/jpg" ||
					file.type === "image/png" ||
					file.type === "image/gif" ||
					file.type === "image/jpeg";

				if (!isJpgOrPng) {
					message.error("图片格式不正确!");
				}
				const isLt2M = file.size / 1024 / 1024 < 5;

				if (!isLt2M) {
					message.error("图片大小不超过5MB!");
				}
				return isJpgOrPng && isLt2M;
			};
			const uploadLogo = async (file) => {
				uploadImage(file, "fileList");
			};
			const uploadBuisness = (file) => {
				uploadImage(file, "business_license");
			};
			const uploadMedical = (file) => {
				uploadImage(file, "medical_license");
			};
			/*
			公共的上传图片函数

			*/
			const uploadEnviroment = async (file) => {
				let formData = new FormData();
				formData.append("file", file.file);
				let res = await uploadPicture(formData, "ali");
				// // url存入列表中,为什么是两个fileList
				data.env_imgs_url = data.env_imgs_url.filter((el) => el.status == "done");
				if (res.success) {
					data.env_imgs_url.push({
						uid: file.file.uid,
						url: res.object,
						status: "done",
						name: file.file.name,
					});
				}
				// console.log(data.env_imgs_url, "env_imgs_url");
			};

			// 公共的上传图片
			const uploadImage = async (file, e) => {
				let formData = new FormData();
				formData.append("file", file.file);
				let res = await uploadPicture(formData, "ali");
				// // url存入列表中,为什么是两个fileList
				data[e] = data[e].filter((el) => el.status == "done");
				if (res.success) {
					data[e].push({
						uid: file.file.uid,
						url: res.object,
						status: "done",
						name: file.file.name,
					});
				}
				// console.log(data[e], "data[e]是--");
			};
			// 分页器改变的时候
			const handleTableChange = (pagination, filters, sorter) => {
				console.log(pagination, "当前分页");
				page.current = pagination.current;
				page.pageSize = pagination.pageSize;
				// 请求列表接口
				init();
			};
			const shopHandleTableChange = (pagination, filters, sorter) => {
				console.log(pagination, "当前分页");
				shopPage.current = pagination.current;
				shopPage.pageSize = pagination.pageSize;
				// 请求商品列表接口
				shopList();
			};
			// 搜索城市
			const searchCity = throttle(async () => {
				//   let url =
				//     "https://restapi.amap.com/v3/place/text?key=77414f92d5cde517e199c03ab4258fda";
				//   let res = await axios.get(
				//     `${url}&keywords=${data.form.city_name}&types=城市`
				//   );
				//   res.data.pois.forEach((el) => (el.value = el.cityname));
				//   data.cityList = res.data.pois;
				//   console.log(data.cityList, "地址列表是");
			}, 500);
			const searchAddress = throttle(async (e) => {
				if (!e.target.value) return;
				//   let url =
				//     "https://restapi.amap.com/v3/place/text?key=77414f92d5cde517e199c03ab4258fda";
				//   let res = await axios.get(`${url}&keywords=${e.target.value}`);
				//   res.data.pois.forEach(
				//     (el) => (el.value = el.pname + el.adname + el.address)
				//   );
				//   data.addressList = res.data.pois;
				//   console.log(data.addressList, "data.addressList");
				let url1 =
					"https://restapi.amap.com/v3/geocode/geo?key=77414f92d5cde517e199c03ab4258fda";
				let res1 = await axios.get(
					`${url1}&address=${e.target.value}&city=${data.form.city_name}`
				);

				let location = res1.data.geocodes[0].location.split(",");
				data.form.point_x = location[0];
				data.form.point_y = location[1];
			}, 500);

			// 上传门店
			const submit = () => {
				// type： publish 发布 update 更新
				data.form.env_imgs_url = data.env_imgs_url.length ?
					JSON.stringify(data.env_imgs_url.map((el) => el.url)) :
					""; //环境图
				data.form.logo = data.fileList.length ? data.fileList[0].url : "";
				data.form.business_license = data.business_license.length ?
					data.business_license.map((el) => el.url).join(",") :
					"";
				data.form.medical_license = data.medical_license.length ?
					data.medical_license.map((el) => el.url).join(",") :
					"";
				data.form.type = data.editType == 0 ? "publish" : "update";
				console.log(data.form, "data.form---");
				// return;

				data.form.online_report = 0; //是否支付在线报告、目前先写0
				data.form.report_way = false; //线上体检报告几天出具（如果有电子报告必填）
				data.form.category = 3; //类目：目前默认是体检
				// deleteObjBlank(data.form)
				data.formRef.validate().then(async () => {
					let res = await updateStore(data.form);
					if (res.success) {
						close("visible");
						init();
					}
				});
			};

			// 关联商品
			const contact = () => {
				data.storeVisible = true;
			};
			//查看详情
			const look = (e) => {
				initDetail(e);
				data.editType = 2;
				data.visible = true;
			};

			async function initDetail(id) {
				let res = await selectShopById(id);
				if (res.success) {}
			}

			// 获取门店列表
			init();
			async function init() {
				let obj = {
					pageNum: page.current,
					pageSize: page.pageSize,
					...data.searchForm,
				};
				let res = await getStoreList(obj);
				if (res.success) {
					data.list = res.object.list;
					page.total = res.object.total;
					data.loading = false;
				}
			}

			return {
				...toRefs(data),
				storeStatusList,
				colums,
				orderStatus,
				orderListStatusColor,
				pagination,
				close,
				storeTypeList,
				add,
				rules,
				labelCol: {
					style: {
						fontWeight: "bold"
					}
				},
				uploadLogo,
				beforeUpload,
				handleChange,
				submit,
				searchCity,
				searchAddress,
				uploadEnviroment,
				uploadBuisness,
				uploadMedical,
				edit,
				colums1,
				contact,
				look,
				title,
				handleTableChange,
				handleChangeFile,
				beforeUpload1,
				uploadImage1,
				bind,
				storeSolums,
				rowSelection,
				rowSelection1,
				shopSolums,
				shopPage,
				shopPagination,
				shopHandleTableChange,
				shopList,
				bindSubmit,
				search,
				rules1,
				searchRef,
				cancleOrder,
				bindAll,
			};
		},
	};
</script>
<style scoped>
	.search {
		margin-bottom: 20px;
	}
</style>